var eventsFilter = {

		jsonData: null,
		combosIdDataArray: null,
		innerHtml: '',
		listeners: null,
		cleanFilters: false,
		features: new Array(),
		actualFilters: new Array(),
		
		initialize: function(config){
			this.listeners = new Array();
			this.combosIdDataArray = new Array();
			var oThis = this;
			$.ajax({
				contentType: "application/x-www-form-urlencoded; charset=iso-8859-1",
				dataType: "json",
				url: config,
				success: function(jsonData){
					oThis.jsonData = jsonData;
					oThis.loadItems();
				}
			});
		},
		
		register: function(who){
			this.listeners.push(who);
		},
		
		loadItems: function(){
			var columns = this.jsonData.columns;
			var col = 0;
			var items = this.jsonData.items;
			this.innerHtml = '<table width="100%">';
			for(var i = 0;i<items.length; i++){
				var item = items[i];
				//Comprobamos la columna a la que pertenece
				if(col == 0){
					this.innerHtml += '<tr><td>';
				}
				else if(col < columns){
					this.innerHtml += '<td>';
				}
				col++;
				//Comprobamos que tenemos que hacer
				if(item.config.type == "combo"){					
					this.innerHtml += '<div id="'+item.config.id+'_combo'+'"></div>';
				}	
				else if(item.config.type == "map"){
					this.innerHtml += '<b><button class="clear_filter_button" type="button" onclick="eventsFilter.loadMap(\''+item.config.id+'_map\')">'+item.config.label+'</button>';
				}
				this.innerHtml += '</td>';
				//Comprobamos si es el ultimo elemento de la lista
				if(col == columns){									
					col = 0;
					this.innerHtml += '</tr>';				
				}
			}
			//Finalizamos la lista
			if(col != 0){
				this.innerHtml += '</tr>';
			}
			this.innerHtml += '</table>';
		},
		
		render: function(div, innerHtml, collapsed, features){
			if(this.jsonData != null){
				if(features != null){
					this.features = features;
				}
				this.setFieldSet(div);
				
				div.innerHTML += '<div>'+innerHtml+'</div>';
				
				this.renderFilters();
				$('#'+this.jsonData.id+'_jquery_fieldset').coolfieldset({collapsed:false,speed:"fast"});
			}
			else{
				div.innerHTML += '<div>'+innerHtml+'</div>';
			}
		},
		
		setFieldSet: function(div){
			var html = '<fieldset id="'+this.jsonData.id+'_jquery_fieldset" class="coolfieldset">'+
			'<legend>'+this.jsonData.title+'</legend>'+
			'<div id="'+this.jsonData.id+'_fieldSet">'+
			this.innerHtml +
			'</div>';
			if(this.cleanFilters){
				html += '<button class="clear_filter_button" type="button" onclick="eventsFilter.clearFilters()">Limpiar filtros</button>'; 
			}
			html += '</fieldset>';
			
			div.innerHTML += html;
		},
		
		loadMap: function(filterId){
			var oThis = this;
			popup.loadPopup();
			popup.centerPopup();
			if(map.map == null){
				map.init("map_div", "Filtros", this.features, null);
				map.map.events.register("click", null , function(e){
					var lonlat = map.map.getLonLatFromPixel(new OpenLayers.Pixel(e.layerX, e.layerY));
					oThis.executeMapFilter(filterId, lonlat);
				});
			}
			else{
				map.updateFeatures(this.features);
			}
		},
		
		clearFilters: function(){
			this.cleanFilters = false;
			this.actualFilters = new Array();
			category.loadContent();
		},
		
		renderFilters: function(){
			//Load combos
			var oThis = this;
			for(var i=0; i<this.jsonData.items.length; i++){
				var item = this.jsonData.items[i];
				var value = "";
				for(var j=0; j<this.actualFilters.length; j++){
					if(this.actualFilters[j].item.config.id == item.config.id){
						value = this.actualFilters[j].data.text;
					}
				}
				if(value == ""){
					value = item.config.label;
				}
				if(item.loadConfig.data){
					$('#'+item.config.id+'_combo').ddslick({
					    data: item.loadConfig.data,
					    selectText: value,
					    width: item.config.width,
					    onSelected: function(selectedData){
					    	var item = oThis.getItemById( selectedData.original[0].id);
					    	if(item != null)
					    		oThis.onValueSelected(selectedData.selectedData, item);
					    }   
					});
				}else if(item.loadConfig.sql){
					$.ajax({
						text: value,
						item: item,
						dataType: "json",
						data: {
							request: "GETCOMBODATA",
							query: item.loadConfig.sql
						},
						url: oThis.jsonData.url,
						success: function(jsonData){
							if(jsonData.success){;
								$('#'+this.item.config.id+'_combo').ddslick({
								    data:jsonData.data,
								    selectText: this.text,
								    width: this.item.config.width,
								    onSelected: function(selectedData){
								    	var item = oThis.getItemById( selectedData.original[0].id);
								    	if(item != null)
								    		oThis.onValueSelected(selectedData.selectedData, item);
								    }   
								});
							}
						}
					});
				}
			}
		},
		
		getItemById: function(id){
			id = id.split("_");
			if(id instanceof Array){
				id = id[0];
			}
			for(var i=0; i< this.jsonData.items.length; i++){
				if(this.jsonData.items[i].config.id == id){
					return this.jsonData.items[i];
				}
			}
			return null;
		},
		
		executeMapFilter: function(filterId, lonlat){
			var geometry = "ST_GeomFromText('POINT("+lonlat.lon+" "+lonlat.lat+")', 4326)";
			var item = this.getItemById(filterId);
			var data = {value: geometry};
			this.onValueSelected(data, item);
			popup.disablePopup();
		},
		
		onValueSelected: function(data, item){
			
			this.cleanFilters += true;
			var updated = false;
			for(var i=0; i<this.actualFilters.length; i++){
				if(this.actualFilters[i].item.config.id == item.config.id){
					this.actualFilters[i] = {item: item, data: data};
					updated = true;
				}
			}
			if(!updated){
				this.actualFilters.push({item: item, data: data});
			}
			var sql = this.createSql();
			for(var i = 0; i<this.listeners.length; i++){
				if(this.listeners[i].loadFilterData){
					this.listeners[i].loadFilterData(sql, this.jsonData.id);
				}
			}
		},
		
		createSql: function(){
			
			
			var sql = "";
			var select = this.jsonData.select;
			var where = "";
			var from = this.jsonData.from;
			var groupBy = this.jsonData.groupBy;
			var orderBy = "";
			var limit = "";
			
			for(var i = 0; i<this.actualFilters.length;i++){
				var item = this.actualFilters[i].item;
				var data = this.actualFilters[i].data;
				
				var itemSelect = item.filter.select;
				var itemWhere = item.filter.where;
				var itemGroupBy = item.filter.groupBy;
				var itemOrderBy = item.filter.orderBy;
				var itemLimit = item.filter.limit;
				
				if(data.value instanceof Array){
					if(itemSelect != null){
						for(var j=0; j<data.value.length; j++){
							while (itemSelect.match("#value"+j+"#")){
								itemSelect = itemSelect.replace("#value"+j+"#", data.value[j]);
							}
						}
						select += " ,"+itemSelect;
					}
					if(itemWhere != null){
						for(var j=0; j<data.value.length; j++){
							while (itemWhere.match("#value"+j+"#")){
								itemWhere = itemWhere.replace("#value"+j+"#", data.value[j]);
							}
						}
						if(where != ""){
							where += " AND "+itemWhere;
						}
						else{
							where = " WHERE "+itemWhere;
						}
					}
					if(itemGroupBy != null){
						for(var j=0; j<data.value.length; j++){
							while (itemGroupBy.match("#value"+j+"#")){
								itemGroupBy = itemGroupBy.replace("#value"+j+"#", data.value[j]);
							}
						}
						if(groupBy != ""){
							groupBy += ","+itemGroupBy;
						}
						else{
							groupBy = " GROUP BY "+itemGroupBy;
						}
					}
					if(itemOrderBy != null){
						for(var j=0; j<data.value.length; j++){
							while (itemOrderBy.match("#value"+j+"#")){
								itemOrderBy = itemOrderBy.replace("#value"+j+"#", data.value[j]);
							}
						}
						if(orderBy != ""){
							orderBy += ","+itemOrderBy;
						}
						else{
							orderBy = " ORDER BY "+itemOrderBy;
						}
					}
				}else{
					if(itemSelect != null){
						while (itemSelect.match("#value#")){
							itemSelect = itemSelect.replace("#value#", data.value);
						}
						select += " ,"+itemSelect;
					}
					if(itemWhere != null){
						while (itemWhere.match("#value#")){
							itemWhere = itemWhere.replace("#value#", data.value);
						}
						if(where != ""){
							where += " AND "+itemWhere;
						}
						else{
							where = " WHERE "+ itemWhere;
						}
					}
					if(itemGroupBy != null){
						while (itemGroupBy.match("#value#")){
							itemGroupBy = itemGroupBy.replace("#value#", data.value);
						}
						if(groupBy != ""){
							groupBy += ","+itemGroupBy;
						}
						else{
							groupBy = " GROUP BY "+itemGroupBy;
						}
					}
					if(itemOrderBy != null){
						while (itemOrderBy.match("#value#")){
							itemOrderBy = itemOrderBy.replace("#value#", data.value);
						}
						if(orderBy != ""){
							orderBy += ","+itemOrderBy;
						}
						else{
							orderBy = " ORDER BY "+itemOrderBy;
						}
					}
					if(itemLimit){
						limit = itemLimit;
					}
				}
			}
			sql = select +" "+from+" "+where+" "+groupBy+" "+orderBy+" "+limit;
			return sql;
		}
		
};